﻿using System.Collections.Generic;
using AutoMapper;
using Portal.Model;
using System;
using System.Linq;
using RepositoryFramework;

namespace Portal.Repository
{
	/// <summary>
	/// Class <see cref="ContactInfoRepository"/> define repository of contact info
	/// </summary>
	public class ContactInfoRepository : GenericRepository<PortalEntities, ContactInfo>, IContactInfoRepository
	{
		#region .ctor

		/// <summary>
		/// Class <see cref="ContactInfoRepository"/> constructor
		/// </summary>
		/// <param name="entities"></param>
		public ContactInfoRepository(PortalEntities entities)
			: base(entities)
		{

		}

		#endregion .ctor

		#region Methods
		/// <summary>
		/// Add or update user
		/// </summary>
		/// <param name="user">The user</param>
		/// <param name="repository">The repository</param>
		/// <param name="contactInfo">The contact info</param>
		public IContactInfo AddOrUpdate(IUser user, IContactInfo contactInfo)
		{
			if (contactInfo == null)
			{
				return null;
			}

			if (user == null)
			{
				throw new ArgumentNullException("user");
			}

			var current = Get(i => i.Id == contactInfo.Id).FirstOrDefault();
			if (current != null)
			{
				contactInfo.MapUpdate<IContactInfo, ContactInfo>(current);
				Update(current);
				return current;
			}
			else
			{
				current = new ContactInfo();
				contactInfo.MapUpdate<IContactInfo, ContactInfo>(current);
				current.UserId = user.Id;
				base.Insert(current);
			}
						return current;
		}

		/// <summary>
		/// Delete all user contact infos
		/// </summary>
		/// <param name="user">The user</param>
		/// <param name="repository">The repository</param>
		public void DeleteAllBy(IUser user)
		{
			if (user == null)
			{
				return;
			}
			var infos = Get(i => i.User.Id == user.Id);
			infos.Each(i => Delete(i));
		}

		/// <summary>
		/// Gets user contact infos by its login
		/// </summary>
		/// <param name="login"></param>
		/// <returns>User</returns>
		public IEnumerable<IContactInfo> GetAllBy(string login)
		{
			var result = Get(i => i.User.Login == login);
			return result;
		}
		#endregion
	}
}